#include "http.h"

char*  request(char buffer[])
{
  int index=strcspn(buffer," ");
  if(index==0)
    return NULL;
        
  char *result=(char*) malloc(index);
  int i;
  for(i=0;i<index;i++)
    result[i]=buffer[i];
        
  return result;
}


int get_response_header(char* res, char response[])
{
  if(rindex(res, '.') != NULL)
    strcpy(response, rindex(res, '.'));

  if(!strcmp(response, ".html"))	
    sprintf(response, "HTTP/1.1 200 OK\r\nServer: Wireless-722/1.0\r\nContent-Type: text/html\r\n\r\n");
  else if(!strcmp(response, ".css"))
    sprintf(response, "HTTP/1.1 200 OK\r\nServer: Wireless-722/1.0\r\nContent-Type: text/css\r\n\r\n");
  else if(!strcmp(response, ".js"))
    sprintf(response, "HTTP/1.1 200 OK\r\nServer: Wireless-722/1.0\r\nContent-Type: application/x-javascript\r\n\r\n");
  else 
    return 0;

  return 1;
}


int get_post_uri(char* uri, char name[])
{
  printf("name:%s\n", name);
  if(!rindex(uri, '/'))
    return 0;

  strcpy(name, rindex(uri, '/'));
  return 1;
}

int get_request_params(char* req)
{
  char tmp[2048], tmp2[2048];
  int idx = 0;
  int length = strlen(req);
  int slen = 0;

#ifdef _DEBUG
  printf("get request params coming\n");
  printf("req content ...\n----------------\n%s\n-------------------\n", req);
#endif

  bzero(tmp, 2048);
  if(strstr(req, "\r\n\r\n") != NULL)
    strcpy(tmp, strstr(req, "\r\n\r\n"));

#ifdef _DEBUG
  printf("strcpy to tmp end...\n");
  printf("tmp is %s\ntmp is end...\n", tmp);
#endif

  strcpy(tmp2, index(tmp, '\n'));
  strcpy(tmp, index(tmp2, '\r'));
  strcpy(tmp2, index(tmp, '\n'));

#ifdef _DEBUG 
  printf("tmp2 copy end...\n");
  printf("%s\n", tmp2);
  printf("tmp2 print end...j\n");
#endif
 
  length = idx = 0;
  int l = 0;

#ifdef _DEBUG
  printf("while routing begin...\n");
#endif

  while(strlen(tmp2) > 1)
  {

#ifdef _DEBUG
  printf("%s\n", tmp2);
  printf("part2 ... OK\n");
#endif
   
    l = 0;
    while(tmp2[1 + l] != '=')
    {
      name[idx][l++] = tmp2[1 + l];
    }
    name[idx][l] = '\0';
    strcpy(tmp, index(tmp2, '='));
    length = 0;
    slen = strlen(tmp);
    
#ifdef _DEBUG
  printf("part3 ... OK\n");
#endif

    l = 0;
    while(1 + length < slen && tmp[1 + length] != '&')
    {
      value[idx][l ++] = tmp[1 + length];
      length ++;
    }
    value[idx][l] = '\0';

    if(!index(tmp, '&'))
      return idx + 1;
    strcpy(tmp2, index(tmp, '&'));
    idx ++;
    
    #ifdef _DEBUG
      printf("while routing.\n");
    #endif
  }

  return idx;
}


char* fileAddress(char buffer[])
{
  printf("Long ::::::::::::%s\n", buffer);
  char temp2[1024], temp[1024];
  strcpy(temp2, strstr(buffer," "));
  strcpy(temp, strstr(temp2, "/"));
  int index=strcspn(temp," ");
  if(index==0)
    return NULL;

#ifdef _DEBUG
  printf("index: %d\n", index);
#endif

  char *result=(char*)malloc(index);
  
  int i;
  for(i=0;i<index;i++)
    result[i]=temp[i];
  result[i] = '\0';
 
  printf("result:%s\n", result); 
  return result;
}
